<?php
	include("gen.php");
	$cmd=get_datan("cmd");
	switch($cmd){
		case 1:
			//get one region based on id
			get_region();
			break;
			
			case 2:
			//get all regions
			get_all_regions();
			break;

			case 3:
			//update region
			update_region();
			break;
			
			case 4:
			//delete region
			delete_region();
			break;
			
			case 5:
			//add region
			add_region();
			break;

		default:
			echo "{";
			echo jsonn("result",0). ",";
			echo jsons("message","unknown command");
			echo "}";
			
			
	}
	
	
	function get_region(){
		include_once("region.php");
		
		$id=get_datan("id");
		$v=new region();
		$row=$v->get_region($id);
		if(!$row){
			echo "{";
			echo jsonn("result",0). ",";
			echo jsons("message","region not found");
			echo "}";
			return;
		}
		
		echo "{";
			echo jsonn("result",1) .",";
			echo '"region":{';
			echo jsonn("id",$id).",";
			echo jsons("regionName",$row['region_name']).",";
			echo jsons("capital",$row['region_capital']);
			echo "}";
		echo "}";
	}
	
	function get_all_regions(){
		include_once("region.php");
		
		$v=new region();
		$row=$v->get_all_region();
		$row=$v->fetch();
		
		echo "{";
			echo jsonn("result",1) .",";
			echo '"regions":{';
			while($row){
			echo jsonn("id",$row['region_id']).",";
			echo jsons("regionName",$row['region_name']).",";
			echo jsons("capital",$row['region_capital']);
			$row=$v->fetch();	
			}
			echo "}";
		echo "}";
		
	}
	
	function update_region(){
		$id=get_datan('id');
		$region_name=get_data('rn');
		$region_capital=get_data('rc');
		if(!$id)
		{
		//return error message
		echo'{"result":0, "message":"id not correct"}';
		return;
		}
		include_once("region.php");
		$v=new region();
		$update=$v->update_region($id,$region_name,$region_capital);
		if($update){
		echo'{"result":1,"message":"updated"}';
		}
		else{
		echo'{"result":0,"message":"id not found"}';
		echo mysql_error();
		}
	}
	
	function delete_region(){
		$id=get_datan('id');
		if(!$id)
		{
		//return error message
		echo'{"result":0, "message":"id not correct"}';
		return;
		}
		include_once("region.php");
		$v=new region();
		$delete=$v->delete_region($id);
		if($delete){
		echo'{"result":1,"message":"successfully deleted"}';
		}
		else{
		echo'{"result":0,"message":"id not found"}';
		echo mysql_error();
		}
	}
	
	function add_region(){
		$id=get_datan('id');
		$region_name=get_data('rn');
		$region_capital=get_data('rc');
	
		include_once("region.php");
		$v=new region();
		$add=$v->add_region($id,$region_name,$region_capital);
		if($add){
		echo'{"result":1,"message":"new region added"}';
		}
		else{
		echo'{"result":0,"message":"unable to add"}';
		echo mysql_error();
		}
	}
?>